// 表单验证相关
import $ from '@/common'
import Field from 'field/type'
export default {
  state: {

  },
  getters: {
    validate(state) {
      if (state.enableValidate) {
        for (let i in state.fields) {
          let field = state.fields[i]
          // 若验证未通过切处于正常输入状态，则表单整体验证未通过
          if (!field.vaild && field.enable && field.show && field.enableValidate) {
            return false
          }
        }
        return true
      } else {
        return true
      }
    }
  },
  actions: {
    // 全部字段验证
    doValidate({commit, dispatch, state}) {
      commit('setValidate', true)
      if (!state.enableValidate) return
      for (let code in state.fields) {
        dispatch('fieldValidate', code)
        if (!state.fields[code].validate) {
          commit('setValidate', false)
        }
      }
    },
    // 单字段验证
    fieldValidate({state, commit}, code) {
      var field = state.fields[code]
      var value = state.data[code]
      var vaild = true
      var type = null

      // 特殊状态跳过验证
      if (field.show === false || field.enable === false) {
        commit('setFieldValidate', {
          code,
          value: vaild,
        type})
        return
      }
      // 否空验证
      if (field.require) {
        if ($.valueNull(value)) {
          vaild = false
          type = 'require'
        }
      }
      // 数据类型格式验证
      if (Field[field.type] && Field[field.type].regExp) {
        if (value.match && !value.match(Field[field.type].regExp)) {
          vaild = false
          type = 'format'
        }
      }
      commit('setFieldValidate', {
        code,
        value: vaild,
      type})
    }
  },
  mutations: {
    setValidate(state, v) {
      state.validate = v
    },
    setFieldValidate(state, {code, value, type}) {
      state.fields[code].validate = value
      if (!value) {
        state.fields[code].validateType = type
        state.validate = false
      } else if (!state.validate) {
        for (let i in state.fields) {
          if (!state.fields[i].validate) {
            return
          }
        }
        state.validate = true
      }
    }
  }
}
